package com.example.tang.zhayan.ui;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tang.zhayan.R;
import com.mob.tools.utils.UIHandler;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

/**
 * 点击个人进入用户登录界面
 */

@ContentView(R.layout.activity_personal)
public class UserLoginActivity extends AppCompatActivity implements PlatformActionListener, Handler.Callback {

    @ViewInject(R.id.back_iv)
    private ImageView ivBack;

    @ViewInject(R.id.phone_num_ed)
    private EditText etPhoneNum;

    @ViewInject(R.id.password_ed)
    private EditText etPassword;

    @ViewInject(R.id.ignore_password_tv)
    private TextView tvIgnorePassword;

    @ViewInject(R.id.sign_up_ll)
    private LinearLayout llSignUp;

    @ViewInject(R.id.log_in_ll)
    private LinearLayout llLogin;

    @ViewInject(R.id.qq_login_iv)
    private LinearLayout ivQqLogin;

    @ViewInject(R.id.weixin_login_iv)
    private LinearLayout ivWeixinLogin;

    @ViewInject(R.id.weibo_login_iv)
    private LinearLayout ivWeiboLogin;

    private Platform platform = null;
    private PlatformDb platformDb = null;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String icon = "";
    private String userName = "";
    private String gender = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        preferences = getSharedPreferences("userMsg", Context.MODE_PRIVATE);
    }


    @Event(value = {R.id.back_iv, R.id.ignore_password_tv, R.id.sign_up_ll, R.id.log_in_ll, R.id.qq_login_iv, R.id.weixin_login_iv, R.id.weibo_login_iv})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_iv:
                this.finish();
                break;
            case R.id.ignore_password_tv:
                Intent findPassword = new Intent(this, FindPasswordActivity.class);
                startActivity(findPassword);
                break;
            case R.id.sign_up_ll:
                // TODO: 2015/12/14 跳转到用户注册界面
                Intent signUp = new Intent(this, SignUpActivity.class);
                startActivity(signUp);
                break;
            case R.id.log_in_ll:
                String phoneNum = etPhoneNum.getText().toString();
                String password = etPassword.getText().toString();
                if (!phoneNum.equals("") && !password.equals("")) {
                    // TODO: 2015/12/14 登录
                } else {
                    Toast.makeText(this, "手机号或密码不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.qq_login_iv:
                platform = ShareSDK.getPlatform(QQ.NAME);
                platform.SSOSetting(false);
                platformDb = platform.getDb();
                if (platformDb != null && platformDb.isValid()) {
                    icon = platformDb.getUserIcon();
                    userName = platformDb.getUserName();
                    gender = platformDb.getUserGender();
                    editor = preferences.edit();
                    editor.putString("icon", icon);
                    editor.putString("userName", userName);
                    editor.putString("gender", gender);
                    editor.commit();
                } else {
                    platform.setPlatformActionListener(new MyPlatformActionListener());
                    platform.authorize();
                }
                Intent intent = new Intent(this, UserActivity.class);
                intent.putExtra("icon", icon);
                intent.putExtra("userName", userName);
                startActivity(intent);
                break;
            case R.id.weixin_login_iv:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                platform.SSOSetting(false);
                platformDb = platform.getDb();

                if (platformDb != null && platformDb.isValid()) {
                    String icon = platformDb.getUserIcon();
                    String userName = platformDb.getUserName();
                    editor.putString("icon", icon);
                    editor.putString("userName", userName);
                    editor.commit();
                } else {
                    platform.setPlatformActionListener(new MyPlatformActionListener());
                    platform.authorize();
                }

                break;
            case R.id.weibo_login_iv:
                // TODO: 2015/12/14 第三方登录  weibo
                break;
        }
    }

    /**
     * 登录成功后 返回直接结束掉这个界面
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        this.finish();
    }

    /**
     * 登录返回接口接收器
     */
    class MyPlatformActionListener implements PlatformActionListener {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
        }

        @Override
        public void onCancel(Platform platform, int i) {
        }
    }


    /**
     * PlatformActionListener的回调接口
     *
     * @param platform
     * @param i
     * @param hashMap
     */

    private static final int MSG_TOAST = 1;
    private static final int MSG_ACTION_CCALLBACK = 2;
    private static final int MSG_CANCEL_NOTIFY = 3;

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        throwable.printStackTrace();
        throwable.getMessage();

        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = throwable;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_TOAST: {
                String text = String.valueOf(msg.obj);
                Toast.makeText(UserLoginActivity.this, text, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_ACTION_CCALLBACK: {
                switch (msg.arg1) {
                    case 1: { // 成功, successful notification
                        showNotification(2000, "Auth successfully");
                    }
                    break;
                    case 2: { // 失败, fail notification
                        String expName = msg.obj.getClass().getSimpleName();
                        if ("WechatClientNotExistException".equals(expName)
                                || "WechatTimelineNotSupportedException".equals(expName)) {
                            showNotification(2000, getString(R.string.wechat_client_inavailable));
                        } else if ("GooglePlusClientNotExistException".equals(expName)) {
                            showNotification(2000, getString(R.string.google_plus_client_inavailable));
                        } else if ("QQClientNotExistException".equals(expName)) {
                            showNotification(2000, getString(R.string.qq_client_inavailable));
                        } else {
                            showNotification(2000, "Auth unsuccessfully");
                        }
                    }
                    break;
                    case 3: { // 取消, cancel notification
                        showNotification(2000, "Cancel authorization");
                    }
                    break;
                }
            }
            break;
            case MSG_CANCEL_NOTIFY: {
                NotificationManager nm = (NotificationManager) msg.obj;
                if (nm != null) {
                    nm.cancel(msg.arg1);
                }
            }
            break;
        }
        return false;
    }

    // 在状态栏提示分享操作,the notification on the status bar
    private void showNotification(long cancelTime, String text) {
        try {
            Context app = getApplicationContext();
            NotificationManager nm = (NotificationManager) app
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            final int id = Integer.MAX_VALUE / 13 + 1;
            nm.cancel(id);

            long when = System.currentTimeMillis();
            Notification notification = new Notification(R.drawable.ic_launcher, text, when);
            PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
//            notification.setLatestEventInfo(app, "sharesdk test", text, pi);
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            nm.notify(id, notification);

            if (cancelTime > 0) {
                Message msg = new Message();
                msg.what = MSG_CANCEL_NOTIFY;
                msg.obj = nm;
                msg.arg1 = id;
                UIHandler.sendMessageDelayed(msg, cancelTime, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
